/*
 * Copyright (c) 2020 hebeiyiliuba.com
 * All rights reserved.
 *
 */
package org.jeecg.modules.wlhy.report;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.third.digitalseal.utils.PdfEditUtil;
import org.jeecg.modules.third.daikai.tongda.dto.ParamDTO;
import org.jeecg.modules.third.daikai.tongda.dto.WaybillsDTO;
import org.jeecg.modules.third.daikai.tongda.service.TongdaApiService;
import org.jeecg.modules.wlhy.bill.entity.HyShippingNoteBill;
import org.jeecg.modules.wlhy.bill.service.IHyShippingNoteBillService;
import org.jeecg.modules.wlhy.customer.entity.HyCustomer;
import org.jeecg.modules.wlhy.customer.service.impl.HyCustomerServiceImpl;
import org.jeecg.modules.wlhy.hydriver.entity.HyDriver;
import org.jeecg.modules.wlhy.hydriver.service.IHyDriverService;
import org.jeecg.modules.wlhy.hyvehicle.entity.HyVehicle;
import org.jeecg.modules.wlhy.hyvehicle.service.impl.HyVehicleServiceImpl;
import org.jeecg.modules.wlhy.order.entity.HyOrder;
import org.jeecg.modules.wlhy.order.service.impl.HyOrderServiceImpl;
import org.jeecg.modules.wlhy.setting.service.IHySettingService;
import org.jeecg.modules.wlhy.shipping.entity.HyShippingNote;
import org.jeecg.modules.wlhy.shipping.entity.TongdaUpDataShippingNoteDTO;
import org.jeecg.modules.wlhy.shipping.mapper.HyShippingNoteMapper;
import org.jeecg.modules.wlhy.shipping.service.IHyShippingNoteService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.math.BigDecimal;
import java.util.*;

/**
 * @BelongsPackage: org.jeecg.modules.wlhy.report
 * @Author: duanlikao
 * @CreateTime: 2022-08-17 09:40
 * @Description: 通达代开
 * @Version: 1.0
 */
@Service
public class ShippingNoteTongdaService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ShippingNoteTongdaService.class);

    @Resource
    private HyShippingNoteMapper hyShippingNoteMapper;

    @Autowired
    private IHyShippingNoteService hyShippingNoteService;

    @Autowired
    private HyVehicleServiceImpl vehicleService;

    @Autowired
    private TongdaApiService tongdaApiService;



    @Autowired
    private HyOrderServiceImpl orderService;

    @Autowired
    private IHyDriverService hyDriverService;

    @Autowired
    private IHyShippingNoteBillService hyShippingNoteBillService;

    @Autowired
    private IHySettingService settingService;

    @Autowired
    private HyCustomerServiceImpl customerService;



    @Value(value = "${jeecg.path.upload}")
    private String uploadpath;

    //银行文件路径
    @Value(value = "${jeecg.path.bank}")
    private String bankPath;


    /**
     *
     * @param page
     * @param queryWrapper
     * @return
     */
    public IPage<TongdaUpDataShippingNoteDTO> getTongdaUpDataPageList(Page<TongdaUpDataShippingNoteDTO> page,
                                                                      QueryWrapper<TongdaUpDataShippingNoteDTO> queryWrapper) {
        IPage<TongdaUpDataShippingNoteDTO> pageList = hyShippingNoteMapper.getTongdaUpDataPageList(page, queryWrapper);
        return pageList;
    }

    /**
     *
     * @param tongdaUpDataShippingNoteDTO
     * @return
     */
    public boolean  uploadTongda(TongdaUpDataShippingNoteDTO tongdaUpDataShippingNoteDTO){

        HyShippingNote shippingNote = hyShippingNoteService.getById(tongdaUpDataShippingNoteDTO.getId());
        if (shippingNote == null) {
            throw new JeecgBootException("该运单上报信息不能为空");
        }


        if(StringUtils.isBlank(tongdaUpDataShippingNoteDTO.getShippingContract())){
            throw new JeecgBootException(tongdaUpDataShippingNoteDTO.getShippingNoteNumber()+"该运单运输合同信息不能为空");
        }
//        if(StringUtils.isBlank(tongdaUpDataShippingNoteDTO.getTrajectoryFile())){
//            throw new JeecgBootException("该运单运输轨迹文件信息不能为空");
//        }

        HyCustomer hyCustomer = customerService.getById(tongdaUpDataShippingNoteDTO.getCustomerId());
        if (hyCustomer == null) {
            throw new JeecgBootException("该运单货主信息不能为空");
        }

        HyOrder hyOrder = orderService.getById(tongdaUpDataShippingNoteDTO.getOrderId());
        if (hyOrder == null) {
            throw new JeecgBootException("该运单货源信息不能为空");
        }

        HyDriver hyDriver = hyDriverService.getById(tongdaUpDataShippingNoteDTO.getDriverId());

        if (hyDriver == null) {
            throw new JeecgBootException("该运单司机信息不能为空");
        }

//        if(StringUtils.isBlank(hyDriver.getQualificationImg()) ){
//            throw new JeecgBootException("司机从业资格证照片不能为空！");
//        }
        if(StringUtils.isNotEmpty(hyDriver.getQualificationImg())){
            if(hyDriver.getQualificationExpiredDate() == null){
                throw new JeecgBootException(hyDriver.getDriverName()+"司机从业资格证有效期不能为空！");
            }
        }


        HyVehicle hyVehicle = vehicleService.getById(tongdaUpDataShippingNoteDTO.getVehicleId());
        if (hyVehicle == null) {
            throw new JeecgBootException("该运单车辆信息不能为空");
        }


        String driverInvoiceAgreement = tongdaUpDataShippingNoteDTO.getInvoiceAgreement();
        if(StringUtils.isBlank(driverInvoiceAgreement)){
            driverInvoiceAgreement  = this.getDriverInvoiceAgreement( hyDriver);
        }
        if(StringUtils.isEmpty(driverInvoiceAgreement)){
            throw new JeecgBootException(hyDriver.getDriverName()+"请联系管理员添加司机税务代开协议模板!");
        }

        LambdaQueryWrapper<HyShippingNoteBill> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(HyShippingNoteBill::getShippingId, tongdaUpDataShippingNoteDTO.getId());
        queryWrapper.eq(HyShippingNoteBill::getBillType, "1");
        HyShippingNoteBill hyShippingNoteBill = hyShippingNoteBillService.getOne(queryWrapper);
        if (hyShippingNoteBill == null) {
            throw new JeecgBootException(tongdaUpDataShippingNoteDTO.getShippingNoteNumber()+"该运单流水单信息不存在！");
        }
        String bankHdImg = StringUtils.EMPTY;
        if(StringUtils.isNotBlank(hyShippingNoteBill.getBankHd())){
            bankHdImg =  tongdaUpDataShippingNoteDTO.getDomainBank()+ hyShippingNoteBill.getBankHd() ;
        }
        if(StringUtils.isNotBlank(hyShippingNoteBill.getBankHdImg())){
            bankHdImg = tongdaUpDataShippingNoteDTO.getDomain()+ hyShippingNoteBill.getBankHdImg();
        }

        if (StringUtils.isEmpty(bankHdImg)) {
            throw new JeecgBootException(tongdaUpDataShippingNoteDTO.getShippingNoteNumber()+"该运单银行回单信息不存在！");
        }
        WaybillsDTO waybillsDTO = this.getWaybillsDTO(tongdaUpDataShippingNoteDTO, hyCustomer, hyOrder, hyDriver, hyVehicle, driverInvoiceAgreement, bankHdImg);

        try {


            ParamDTO paramDTO = new ParamDTO();
            paramDTO.setOnly_update( "0".equals(tongdaUpDataShippingNoteDTO.getTongdaUploadStatus() ) ? 0 : 1) ;
            paramDTO.setWaybill_list(
                    Collections.singletonList(waybillsDTO)
            );
            String res = tongdaApiService.waybillPush(paramDTO);
            if(StringUtils.isBlank(res)){
                throw new JeecgBootException("该运单上报异常请重新推送！");
            }
            JSONObject result = JSONObject.parseObject(res);
            int code =  result.getIntValue("code");
            if(200  == code ){
                shippingNote.setTongdaUploadStatus("1");
                shippingNote.setTongdaUploadDate(new Date());
                hyShippingNoteService.updateById(shippingNote);
                return  true;
            }else{
                String message =  result.getString("message");
                String data =  result.getString("data");
                throw new JeecgBootException(message+data);
            }
        }catch (Exception e){
            shippingNote.setTongdaUploadStatus("2");
            shippingNote.setTongdaUploadDate(new Date());
            hyShippingNoteService.updateById(shippingNote);
            throw new JeecgBootException(e.getMessage());
        }


    }

    private WaybillsDTO getWaybillsDTO(TongdaUpDataShippingNoteDTO tongdaUpDataShippingNoteDTO, HyCustomer hyCustomer, HyOrder hyOrder, HyDriver hyDriver, HyVehicle hyVehicle, String driverInvoiceAgreement, String bankHdImg) {

        WaybillsDTO waybillsDTO = new WaybillsDTO();

        waybillsDTO.setOrder_sn(hyOrder.getOrderNum());
        waybillsDTO.setWaybill_sn(tongdaUpDataShippingNoteDTO.getShippingNoteNumber());
        waybillsDTO.setCompany_name(hyCustomer.getCustomerName());
        waybillsDTO.setGood_name(tongdaUpDataShippingNoteDTO.getDescriptionOfGoods());

        BigDecimal costPayShipping = tongdaUpDataShippingNoteDTO.getDriverFee() ;


        waybillsDTO.setGood_price(costPayShipping.intValue());

        waybillsDTO.setFuel_cost(tongdaUpDataShippingNoteDTO.getGasRechargeAmount() != null ? tongdaUpDataShippingNoteDTO.getGasRechargeAmount().intValue() : 0 );
        waybillsDTO.setCar_leader_cost(tongdaUpDataShippingNoteDTO.getCarrierFee() != null ? tongdaUpDataShippingNoteDTO.getCarrierFee().intValue(): 0 );



        String from_province_id = tongdaUpDataShippingNoteDTO.getSendAreaCode().substring(0,2)+"0000";
        waybillsDTO.setFrom_province_id( Integer.parseInt(from_province_id));
        String from_city_id = tongdaUpDataShippingNoteDTO.getSendAreaCode().substring(0,4)+"00";
        waybillsDTO.setFrom_city_id( Integer.parseInt(from_city_id));
        waybillsDTO.setFrom_county_id(
               Integer.parseInt(tongdaUpDataShippingNoteDTO.getSendAreaCode())
        );
        waybillsDTO.setFrom_address(tongdaUpDataShippingNoteDTO.getSendAddress());
        //装卸货榜单
        List<String> imgLoadingsAll = Arrays.asList(tongdaUpDataShippingNoteDTO.getImgLoading().split(","));
        List<String> imgLoadingsTemp = new ArrayList<>();
        for(String imgLoading : imgLoadingsAll){
            imgLoadingsTemp.add(tongdaUpDataShippingNoteDTO.getDomain()+imgLoading);  ;
        }
        waybillsDTO.setDeliver_img( StringUtils.join(imgLoadingsTemp, ",") );

        String target_province_id = tongdaUpDataShippingNoteDTO.getReceiveAreaCode().substring(0,2)+"0000";
        waybillsDTO.setTarget_province_id( Integer.parseInt(target_province_id));
        String target_city_id = tongdaUpDataShippingNoteDTO.getReceiveAreaCode().substring(0,4)+"00";
        waybillsDTO.setTarget_city_id( Integer.parseInt(target_city_id));
        waybillsDTO.setTarget_county_id(
                Integer.parseInt(tongdaUpDataShippingNoteDTO.getReceiveAreaCode())
        );
        waybillsDTO.setTarget_address(tongdaUpDataShippingNoteDTO.getReceiveAddress());
        waybillsDTO.setReceiving_contact_name(tongdaUpDataShippingNoteDTO.getReceiveContactName());
        waybillsDTO.setReceiving_contact_mobile(tongdaUpDataShippingNoteDTO.getReceiveContactTel());
        //装卸货榜单
        List<String> imgUnloadingsAll = Arrays.asList(tongdaUpDataShippingNoteDTO.getImgUnloading().split(","));
        List<String> imgUnloadingsTemp = new ArrayList<>();
        for(String imgUnloading : imgUnloadingsAll){
            imgUnloadingsTemp.add(tongdaUpDataShippingNoteDTO.getDomain()+imgUnloading);  ;
        }

        waybillsDTO.setReceiving_img(  StringUtils.join(imgUnloadingsTemp, ",") );

        waybillsDTO.setReal_delivery_time(
                DateUtils.dateTimeToString(tongdaUpDataShippingNoteDTO.getStatusDtLoading())
        );
        waybillsDTO.setReal_receiving_time(
                DateUtils.dateTimeToString(tongdaUpDataShippingNoteDTO.getStatusDtUnloading())
        );
        waybillsDTO.setSign_name(tongdaUpDataShippingNoteDTO.getUpdateBy());
        waybillsDTO.setSign_mobile(hyCustomer.getLoginPhone());
        waybillsDTO.setNo_trajector_prove(
               StringUtils.isNotBlank(tongdaUpDataShippingNoteDTO.getTrajectoryFile()) ?
                       tongdaUpDataShippingNoteDTO.getDomain()+ tongdaUpDataShippingNoteDTO.getTrajectoryFile() :
                       StringUtils.EMPTY
        );
        waybillsDTO.setPay_voucher_img(
               bankHdImg
        );
        waybillsDTO.setTrade_file(
                tongdaUpDataShippingNoteDTO.getDomain()+ tongdaUpDataShippingNoteDTO.getShippingContract()
        );
        waybillsDTO.setDrivers_wt_img(
                tongdaUpDataShippingNoteDTO.getDomain()+ driverInvoiceAgreement
        );

        //车辆信息
        waybillsDTO.setLicense_plate(hyVehicle.getVehicleNumber());

        waybillsDTO.setVehicle_license(tongdaUpDataShippingNoteDTO.getDomain()+hyVehicle.getDrivingLicenseImg());
        waybillsDTO.setVehicle_license_positive(tongdaUpDataShippingNoteDTO.getDomain()+hyVehicle.getDrivingLicenseImg());
        waybillsDTO.setVehicle_license_reverse(tongdaUpDataShippingNoteDTO.getDomain()+hyVehicle.getDrivingLicenseImg2());
        waybillsDTO.setRoad_transport_img(
                tongdaUpDataShippingNoteDTO.getDomain()+hyVehicle.getRoadTransportImg()
        );

        waybillsDTO.setVehicle_license_register_at(
                DateUtils.date2Str(hyVehicle.getRegisterDate(),DateUtils.date_sdf.get() ) +" 00:00:00"
        );
        waybillsDTO.setVehicle_license_get_at(
                DateUtils.date2Str(hyVehicle.getIssueDate(),DateUtils.date_sdf.get() ) +" 00:00:00"
        );

        Calendar calend = Calendar.getInstance();
        calend.setTime(hyVehicle.getIssueDate());
        calend.add(Calendar.YEAR, +15);
        Date licenseExpire = calend.getTime();

        waybillsDTO.setVehicle_license_expire_at(
                DateUtils.date2Str(licenseExpire,DateUtils.date_sdf.get() ) +" 00:00:00"
        );
        waybillsDTO.setVehicle_license_organ(hyVehicle.getIssuingOrganizations());
        waybillsDTO.setVehicle_identification(
                StringUtils.isNotBlank(hyVehicle.getDrivingLicenseNum()) ? hyVehicle.getDrivingLicenseNum() : hyVehicle.getVin()
        );
        waybillsDTO.setRoad_transport_no(hyVehicle.getRoadTransportNumber());

        //司机信息
        waybillsDTO.setDriver_name(hyDriver.getDriverName());
        waybillsDTO.setDriver_mobile(hyDriver.getTelephone());
        waybillsDTO.setDriver_identity_num(hyDriver.getIdcard());
        waybillsDTO.setDriver_identity_card_positive(
                tongdaUpDataShippingNoteDTO.getDomain()+ hyDriver.getIdcardImg()
        );
        waybillsDTO.setDriver_identity_card_reverse(
                tongdaUpDataShippingNoteDTO.getDomain()+ hyDriver.getIdcardImgBack()
        );
        waybillsDTO.setDriver_identity_card_start(
                DateUtils.date2Str(hyDriver.getIdcardValidFrom(),DateUtils.date_sdf.get() ) +" 00:00:00"
        );
        waybillsDTO.setDriver_identity_card_end(
                DateUtils.date2Str(hyDriver.getIdcardExpiredDate(),DateUtils.date_sdf.get() ) +" 00:00:00"
        );
        waybillsDTO.setDriver_license_num(hyDriver.getIdcard());
        waybillsDTO.setDriver_license_image(
                tongdaUpDataShippingNoteDTO.getDomain()+hyDriver.getDriverImg()
        );
        waybillsDTO.setDriver_license_type(hyDriver.getVehicleClass());

        waybillsDTO.setDriver_license_first_time(
                DateUtils.date2Str(hyDriver.getIssueStartDate(),DateUtils.date_sdf.get() ) +" 00:00:00"
        );
        waybillsDTO.setDriver_license_start_time(
                DateUtils.date2Str(hyDriver.getValidPeriodFrom(),DateUtils.date_sdf.get() ) +" 00:00:00"
        );
        waybillsDTO.setDriver_license_end_time(
                DateUtils.date2Str(hyDriver.getValidPeriodTo(),DateUtils.date_sdf.get() ) +" 00:00:00"
        );
        waybillsDTO.setDriver_license_authority(hyDriver.getIssuingOrganizations());

        if(StringUtils.isNotEmpty(hyDriver.getQualificationImg())){
            waybillsDTO.setQualification_cert_image(
                    tongdaUpDataShippingNoteDTO.getDomain()+hyDriver.getQualificationImg()
            );
            Calendar calend1 = Calendar.getInstance();
            calend1.setTime(hyDriver.getQualificationExpiredDate());
            calend1.add(Calendar.YEAR, -10);
            Date qualificationStartTime = calend1.getTime();
            waybillsDTO.setQualification_cert_start_time(
                    DateUtils.date2Str(qualificationStartTime,DateUtils.date_sdf.get() ) +" 00:00:00"
            );
            waybillsDTO.setQualification_cert_end_time(
                    DateUtils.date2Str(hyDriver.getQualificationExpiredDate(),DateUtils.date_sdf.get() ) +" 00:00:00"
            );
        }

        waybillsDTO.setQualification_cert_no(hyDriver.getIdcard());


        return waybillsDTO;
    }


    /**
     * 获取司机税务代开协议
     * @param hyDriver
     * @return
     */
    public String getDriverInvoiceAgreement(HyDriver hyDriver) {

      String invoiceIssuingAgreement =   settingService.getSettingValueByTag2("invoice_issuing_agreement");
      if(StringUtils.isEmpty(invoiceIssuingAgreement)){
          throw new JeecgBootException("请联系管理员添加司机税务代开协议模板!");
      }
      String fileAddress = uploadpath+ File.separator +invoiceIssuingAgreement ;

       String driverInvoiceAgreement  =  PdfEditUtil.addInvoiceAgreement ( hyDriver,  fileAddress, uploadpath+ File.separator ) ;
       if(StringUtils.isNotBlank(driverInvoiceAgreement)){
           hyDriver.setInvoiceAgreement(driverInvoiceAgreement);
           hyDriverService.updateById(hyDriver);
           return driverInvoiceAgreement;

       }
       return StringUtils.EMPTY;
    }
}
